<template>
  <div class="mine">
    <van-cell-group>
      <van-cell title="单元格" value="内容">
        <template #default>
          <van-image
            width="100"
            height="100"
            :src="'http://localhost:3000' + userinfo.avatar"
          >
            <van-uploader :after-read="afterRead">
              <div class="mask"></div>
            </van-uploader>
          </van-image>
        </template>
      </van-cell>
    </van-cell-group>
  </div>
</template>

<script>
import { getUserinfo, uploadImg, updateUserAvatar } from '@/api/user'
export default {
  data () {
    return {
      userinfo: {}
    }
  },
  async created () {
    this.refreshData()
  },
  methods: {
    async refreshData () {
      const res = await getUserinfo()
      this.userinfo = res.data.data
    },
    async afterRead (file) {
      const formData = new FormData()
      // file.file获取的是图片的信息
      formData.append('file', file.file)
      const res = await uploadImg(formData)
      console.log(res)
      // 图片已经上传成功，接下来将图片和用户进行关联
      const res2 = await updateUserAvatar({
        userId: '66',
        avatar: '/images/avatar/' + res.data.data[0].filename
      })
      console.log(res2)
      this.refreshData()
    }
  }
}
</script>

<style>
.mask {
  width: 100px;
  height: 100px;
  background-color: blue;
}
.van-uploader {
  position: absolute;
  top: 0;
  left: 0;
  opacity: 0;
}
</style>
